<template>
  <div class="custom_batch_wrapper">
    <Layout v-for="(_component, ind) in batchComponents" class="cus_batch_layout" :key="ind">
      <Sider hide-trigger class="cus_batch_sider">
        <span @click="aaa" class="cus_sider_span">{{_component.outerConfig.name}}</span>
      </Sider>
      <Layout :style="{background: '#fff', paddingLeft: '10px'}">
        <Tabs value="baseAttr" v-if="_component">
          <TabPane label="基础属性" name="baseAttr" v-if="Object.keys(_component.outerConfig.config).length">
            <Form class="base-form" :label-width="80" v-for="(value, item) in _component.outerConfig.config" :key="item">
              <!-- 额外配置的在这里显示 -->
              <template v-if="extraConfig[_component.name] && extraConfig[_component.name][item]">
                <FormItem :label="extraConfig[_component.name][item].title" v-show="setConfigShow(item)">
                  <!-- 特殊组件-可以选择当前模板中除了自己外的其他所有组件 高级组件使用的 保留 可能用不到-->
                  <Select filterable multiple :value="value" @on-change="v=>{updateCommonValue2(false, v, item)}" v-if="extraConfig[_component.name][item].componentName === 'idSelect'">
                    <Option v-for="(unit,index) of getOtherComponents()" :value="unit.id" :key="index" @mousedown.native="setCurrentConfig(_component.outerConfig)">{{unit.text}}</Option>
                  </Select>

                  <!-- 下拉框 -->
                  <Select :value="value" @on-change="v=>{updateCommonValue2(false,v,item)}" v-if="extraConfig[_component.name][item].componentName === 'select'">
                    <Option v-for="(unit,index) of extraConfig[_component.name][item].options" :value="unit.value" :key="index" @mousedown.native="setCurrentConfig(_component.outerConfig)">{{unit.label}}</Option>
                  </Select>

                  <!-- 数字框 -->
                  <InputNumber :value="value" @on-change="v=>{updateCommonValue2(false,v,item)}" v-if="extraConfig[_component.name][item].componentName === 'inputNumber'" @mousedown.native="setCurrentConfig(_component.outerConfig)"/>

                  <!-- 数字框--px -->
                  <InputNumber :value="parseInt(value)" @on-change="v=>{updateCommonValue2(false,v,item,true)}" v-if="extraConfig[_component.name][item].componentName === 'inputNumberPx'" @mousedown.native="setCurrentConfig(_component.outerConfig)"/>

                  <!-- 输入框 -->
                  <Input :value="value" @on-change="updateCommonValue2($event,value,item)" v-if="extraConfig[_component.name][item].componentName === 'input'" @mousedown.native="setCurrentConfig(_component.outerConfig)"/>
                  <Input type="textarea" :value="value" :rows="4" @on-change="updateCommonValue2($event,value,item)" v-if="extraConfig[_component.name][item].componentName === 'textarea'" @mousedown.native="setCurrentConfig(_component.outerConfig)"/>

                  <!-- 开关 -->
                  <i-switch :value="value" @on-change="v=>{updateCommonValue2(false,v,item)}" v-if="extraConfig[_component.name][item].componentName === 'switch'" @mousedown.native="setCurrentConfig(_component.outerConfig)"/>

                  <!-- 数据编辑 -->
                  <i class="iconfont icon-file-edit" title="编辑" v-if="extraConfig[_component.name][item].componentName === 'jsoneditor'" @click="editArray(item)" @mousedown.native="setCurrentConfig(_component.outerConfig)"></i>
                </FormItem>
              </template>

              <!-- 已有组件的在这里显示 -->
              <component v-else :is="item" :value="value" @updateValue="updateCommonValue" @mousedown.native="setCurrentConfig(_component.outerConfig)"></component>
            </Form>

            <!-- 校验的配置 -->
            <Form class="base-form" :label-width="80" v-show="_component.valid!==null">
              <FormItem label="组件校验">
                <Icon type="ios-create-outline" :size="20" class="edit_icon" title="编辑" @click="editValid(_component.valid)" @mousedown.native="setCurrentConfig(_component.outerConfig)"/>
                <!-- <i class="iconfont icon-file-edit" title="编辑" @click="editValid(_component.valid)"></i> -->
              </FormItem>
            </Form>
          </TabPane>
        </Tabs>

        <Tabs value="styleAttr" v-if="_component">
          <TabPane label="样式属性" name="styleAttr" v-if="Object.keys(_component.outerConfig.style).length">
            <Form class="base-form" :label-width="80" v-for="(value,item) in _component.outerConfig.style" 
            :key="item">
              <component :is="item" :value="value" @updateValue="updateStyleValue" @mousedown.native="setCurrentConfig(_component.outerConfig)"></component>
            </Form>
          </TabPane>
        </Tabs>
      </Layout>
    </Layout>
    <!-- JSON编辑器 -->
    <Modal width="700px" v-model="jsonEditVisual" title="数据查看/编辑" footer-hide class="visual-array-edit-model">
      <Tooltip :content="tooltipContent" :style="toolTipStyle" max-width="400" v-if="editValidFlag">
        数据示例
      </Tooltip>
      <div id="arrayEdit"></div>
      <div class="array-edit-footer">
        <Button @click="cancelHandler" style="margin-right:8px">取消</Button>
        <Button type="primary" @click="okHandler">确定</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import { iconList } from '@/components/custom/config/icon';
import { extraConfig } from '@/components/custom/config/extra';
// import { deepCopy, typeOf } from 'assets/scripts/common';
// import { mapState, mapActions, mapMutations } from 'vuex';

// 可复用组件
import fontFamily from '@/components/custom/Right/StyleComponent/FontFamily.vue';
import fontSize from '@/components/custom/Right/StyleComponent/FontSize.vue';
import fontWeight from '@/components/custom/Right/StyleComponent/FontWeight.vue';
import fontStyle from '@/components/custom/Right/StyleComponent/FontStyle.vue';
import textDecoration from '@/components/custom/Right/StyleComponent/TextDecoration.vue';
import textAlign from '@/components/custom/Right/StyleComponent/TextAlign.vue';
import backgroundColor from '@/components/custom/Right/StyleComponent/BackgroundColor.vue';
import color from '@/components/custom/Right/StyleComponent/Color.vue';
import borderWidth from '@/components/custom/Right/StyleComponent/BorderWidth.vue';
import borderColor from '@/components/custom/Right/StyleComponent/BorderColor.vue';
import borderStyle from '@/components/custom/Right/StyleComponent/BorderStyle.vue';
import lineHeight from '@/components/custom/Right/StyleComponent/lineHeight.vue';
import marginLeft from '@/components/custom/Right/StyleComponent/MarginLeft.vue';
import marginRight from '@/components/custom/Right/StyleComponent/MarginRight.vue';
import marginTop from '@/components/custom/Right/StyleComponent/MarginTop.vue';
import marginBottom from '@/components/custom/Right/StyleComponent/MarginBottom.vue';
import paddingLeft from '@/components/custom/Right/StyleComponent/PaddingLeft.vue';
import paddingRight from '@/components/custom/Right/StyleComponent/PaddingRight.vue';
import paddingTop from '@/components/custom/Right/StyleComponent/PaddingTop.vue';
import paddingBottom from '@/components/custom/Right/StyleComponent/PaddingBottom.vue';

import placeholder from '@/components/custom/Right/CommonComponent/Placeholder.vue';
import disabled from '@/components/custom/Right/CommonComponent/Disabled.vue';
import size from '@/components/custom/Right/CommonComponent/Size.vue';
import labelName from '@/components/custom/Right/CommonComponent/LabelName.vue';
import labelWidth from '@/components/custom/Right/CommonComponent/LabelWidth.vue';

export default {
  name: 'CustomSetting',
  data() {
    return {
      componentsInfo: [], // 拷贝到本地数据
      extraConfig,
      jsonEditVisual: false,
      arrayEditor: null,
      editName: null,
      editValidFlag: false,
      toolTipStyle: {
        position: 'absolute',
        top: 0,
        lineHeight: '46px',
        right: '50px',
        fontSize: '14px',
        fontWeight: 700,
        cursor: 'pointer'
      },
      tooltipContent: '[{\n' +
        '"required":true,\n' +
        '"pattern": "",\n' +
        '"min": 1,\n' +
        '"max": 10,\n' +
        '"Length": 10,\n' +
        '"message": "错误信息",\n' +
        '"type": "string"\n' +
        '}]',
      currentOutConfig: {}
    }
  },
  props: {
    components: {
      type: Array,
      default: ()=>([])
    }
  },
  created() {
    this.componentsInfo = this.Utils.deepCopy(this.components)
  },
  mounted() {

  },
  // watch: {
  //   "components": {
  //     handler(val){
  //     this.componentsInfo = this.Utils.deepCopy(this.components)
      
  //   console.log(this.components, val, this.componentsInfo, 'console.log(this.components, this.componentsInfo)')
    
  //     },
  //     deep: true
  //   }
  // },  
  computed: {
    // 过滤无需配置的组件
    batchComponents(){
      // 拖拽页面 没有选择对外配置项 返回空对象{};不使用JSON.stringify进行对比，会存在JSON序列号风险
      return this.componentsInfo.filter(item => !!item.outerConfig.config)
    }
  },
  methods: {
    aaa(){
      console.log(this.batchComponents,  'batchComponentsbatchComponents')
      console.log(this.components, 'componentscomponentscomponentscomponents')
    },
    setCurrentConfig( currentConifg ){
      this.currentOutConfig = currentConifg
    },
    // 更改普通设置的值
    updateCommonValue(item) {
      // iview表格的columns会自动生产__id，这个要去除，不然会影响渲染
      if (item.name === 'columns' && this.activeCom.name === 'tableItem') {
        item.value.forEach(unit => {
          delete unit.__id;
        });
      }
      console.log(this.currentOutConfig.config)
      console.log(item.name)
      this.currentOutConfig.config[item.name] = item.value;
    },

    updateCommonValue2(e, value, name, isPx) {
      console.log(e, value, name,'e, value, name,')
      if (e) {
        value = e.target.value;
      }

      this.updateCommonValue({
        name,
        value: isPx ? value + 'px' : value
      });
    },

    // 更新配置中的数据源
    updateCommonSource(data, name) {
      this.updateCommonValue({
        name,
        value: data.id
      });
    },
    // 配置的显示与否
    setConfigShow(item) {
      // if (!this.activeCom || !this.activeCom.name) {
      //   return;
      // }
      // let itemConfig = this.extraConfig[this.activeCom.name][item];
      // if (!itemConfig.precondition) {
      //   return true;
      // } else {
      //   let { name, value } = itemConfig.precondition;
      //   // 当name的值是value的时候才显示
      //   if (this.activeCom.config[name] === value) {
      //     return true;
      //   } else {
      //     return false;
      //   }
      // }
    },

    // 更改样式的值
    updateStyleValue(item) {
      this.currentOutConfig.style[item.name] = item.value;
    },
    // 获取除了当前激活组件外的其他组件信息
    getOtherComponents (currentCom) {
      if (!this.activeCom) {
        return;
      }
      let arr = [];
      let components = JSON.parse(JSON.stringify(this.components))

      components.forEach(item => {
        if (item.id !== this.activeCom.id) {
          item.text = this.componentNames[item.name] + `(${item.id})`;
          arr.push(item);
        }
      });

      return arr;
    },
    // 校验信息
    editValid(valid) {
      // 设置当前outerConfig

      this.jsonEditVisual = true;

      // 表示编辑的是校验信息
      this.editValidFlag = true;

      if (!this.arrayEditor) {
        this.arrayEditor = new this.$jsoneditor(
          document.getElementById('arrayEdit'),
          {
            search: false,
            mode: 'text',
            indentation: 2
          }
        );
      }

      this.arrayEditor.set(valid);
    },
    // 编辑数组/对象
    editArray(name) {
      this.jsonEditVisual = true;
      this.editName = name;

      if (!this.arrayEditor) {
        this.arrayEditor = new this.$jsoneditor(
          document.getElementById('arrayEdit'),
          {
            search: false,
            mode: 'text',
            indentation: 2
          }
        );
      }

      this.arrayEditor.set(this.activeCom.config[name]);
    },
    // 确定编辑
    okHandler() {
      try {
        let value = this.arrayEditor.get();
        // 编辑的是组件的校验信息
        if (this.editValidFlag) {
          if (this.checkData(value)) {
            this.updateVaildValue(value);
          } else {
            return false;
          }
        } else {
          this.updateCommonValue({
            name: this.editName,
            value
          });
        }

        this.cancelHandler();
      } catch (err) {
        console.log(err);
        this.$Message.error('请输入正确的数据');
      }
    },
    // 校验数据格式是否符合规范 value 目标值
    checkData(value) {
      let status = true; // 方法状态
      const that = this;
      const message = '数据格式不符合规范'; // 错误提示
      const typeString = ['min', 'max', 'Length'];
      const original = ['required', 'pattern', 'min', 'max', 'Length', 'message', 'type'];
      const dataType = ['string', 'number', 'boolean', 'object', 'array', 'date', 'float'];
      if (typeOf(value) === 'array') {
        value.forEach(function (vData) {
          Object.keys(vData).every(function (item) {
            if (original.indexOf(item) === -1) {
              status = that.errorNotice(message);
              return status;
            }

            if (item === 'required' && typeOf(vData[item]) !== 'boolean') {
              status = that.errorNotice(message);
              return status;
            }

            if (typeString.indexOf(item) > -1 && (typeOf(vData[item]) !== 'number' && typeOf(vData[item]) !== 'string')) {
              status = that.errorNotice(message);
              return status;
            }

            if (item === 'message' && typeOf(vData[item]) !== 'string') {
              status = that.errorNotice(message);
              return status;
            }

            if (item === 'type' && dataType.indexOf(vData[item]) === -1) {
              status = that.errorNotice(message);
              return status;
            }
            return true
          })
        })
      } else {
        status = that.errorNotice(message)
      }
      return status;
    },
    // 错误提示并返回
    errorNotice(message) {
      this.$Message.error(message);
      return false;
    },
    // 取消编辑
    cancelHandler() {
      this.jsonEditVisual = false;
      this.editValidFlag = false;
      this.editName = null;
    },
    // 外部获取当前组件的值
    getComponentVal(){
      let comVal = {}
      console.log(this.batchComponents, 'batchComponentsbatchComponentsbatchComponents')
      this.batchComponents.forEach(item=>{
        comVal[item.id] = item.outerConfig
      })
      return comVal
    }
  },
  components: {
    // 样式组件
    fontFamily,
    fontSize,
    fontWeight,
    fontStyle,
    textDecoration,
    textAlign,
    backgroundColor,
    color,
    borderWidth,
    borderColor,
    borderStyle,
    lineHeight,
    marginLeft,
    marginRight,
    marginTop,
    marginBottom,
    paddingLeft,
    paddingRight,
    paddingTop,
    paddingBottom,

    // 基础组件
    placeholder,
    disabled,
    size,
    labelName,
    labelWidth
  }
}
</script>

<style lang="less" scoped>
.custom_batch_wrapper {
  padding: 10px 0;
}
.cus_batch_layout {
  margin-bottom: 10px;
}
.cus_batch_sider {
  background-color: #f5f7f9;
  text-align: center;
}
.cus_sider_span {
  position: absolute;
  top: 50%;
  transform: translate3d(-50%, -50%, 0);
  left: 50%;
}
.edit_icon{
  margin-bottom: 5px;
  cursor: pointer;
}
</style>
